from django.shortcuts import render_to_response
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotFound, HttpResponsePermanentRedirect, HttpResponseRedirect
from google.appengine.api import users
from tomatobase.models import *
import logging

def mater_render(template, context):
    """wraps render_to_response with some extra context"""
    user = users.get_current_user()
    if user:
        context['user'] = user
        context['garden'] = Garden.get_garden_by_user(user)
    else:
        context['login_url'] = users.create_login_url('/')
    context['media_url'] = settings.MEDIA_URL
    return render_to_response(template, context)

def loginrequired(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user:
            return func(request, *args, **kw)
        else:
            return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    return _wrapper

def landing_page(request):
    return mater_render('garden.html', {})
                        
@loginrequired
def create_garden(request): # this should really use newforms
    logging.debug("creating garden")
    user = users.get_current_user()
    logging.debug("creating garden for user %s" % user)
    posted = request.POST.copy()
    logging.debug("got params %s" % posted)
    garden = Garden(owner=user, name=posted['name'], description=posted['description'])
    garden.put()
    logging.debug("putted %s" % garden)
    return HttpResponseRedirect('/your_garden/')
